from datetime import datetime, timedelta
import sys
sys.path.append("/")
from app.extensions import db
from app.utils.security import generate_password_hash, check_password_hash


class User(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(128), nullable=False)

    is_active = db.Column(db.Boolean, default=True)
    is_admin = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    last_login = db.Column(db.DateTime, default=datetime.utcnow)
    __table_args__ = {
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_unicode_ci'
    }

    # 关系角色定义
    roles = db.relationship('Role', secondary='user_roles', backref=db.backref('users', lazy='dynamic'))

    # 外键（关联到departments表的id字段）
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'), nullable=False)

    # 定义关系（多对一：多个员工属于一个部门）
    department = db.relationship('Department', back_populates='users')

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return f'<User {self.username}>'

    @staticmethod
    def init_user():
        rets = [(1, 'kgreat', '1551406827@qq.com', generate_password_hash('010079'), True, True, 4)]
        for ret in rets:
            user = User()
            user.id = ret[0]
            user.username = ret[1]
            user.email = ret[2]
            user.password_hash = ret[3]
            user.is_active = ret[4]
            user.is_admin = ret[5]
            user.department_id = ret[6]
            db.session.add(user)

            user.roles.append(Role.query.filter_by(name='general_manager').first())

            user.department = Department.query.filter_by(name='manager_department').first()



        db.session.commit()


class Role(db.Model):
    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    description = db.Column(db.String(255))
    __table_args__ = {
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_unicode_ci'
    }

    def __repr__(self):
        return f'<Role {self.name}>'

    @staticmethod
    def init_role():
        rets = [(1, 'normal_user', '一般用户'),
                (2, 'financial_manager', '财务经理'),
                (3, 'production_manager', '生产经理'),
                (4, 'sale_manager', '销售经理'),
                (5, 'general_manager', '总经理')]
        for ret in rets:
            role = Role()
            role.id = ret[0]
            role.name = ret[1]
            role.description=ret[2]
            db.session.add(role)
        db.session.commit()


class UserRole(db.Model):
    __tablename__ = 'user_roles'

    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), primary_key=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'), primary_key=True)
    __table_args__ = {
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_unicode_ci'
    }

class TokenBlocklist(db.Model):
    __tablename__ = 'token_blocklist'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    jti = db.Column(db.String(36), nullable=False, index=True)
    created_at = db.Column(db.DateTime, nullable=False)
    __table_args__ = {
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_unicode_ci'
    }


class Department(db.Model):
    __tablename__ = 'departments'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    description = db.Column(db.String(255))
    # 定义关系（一对多：一个部门对应多个员工）
    users = db.relationship('User', back_populates='department')
    __table_args__ = {
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_unicode_ci'
    }

    def __repr__(self):
        return f'<Department {self.name}>'

    @staticmethod
    def init_department():
        rets = [(1, 'financial_department', '财务部门'),
                (2, 'production_department', '生产部门'),
                (3, 'sale_department', '销售部门'),
                (4, 'manager_department', '经理部门')]
        for ret in rets:
            department = Department()
            department.id = ret[0]
            department.name = ret[1]
            department.description=ret[2]
            db.session.add(department)
        db.session.commit()



class FinancialBusiness(db.Model):
    __tablename__ = 'financial_business'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(50), unique=True, nullable=False)
    content = db.Column(db.String(255), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    dead_line = db.Column(db.DateTime, default= datetime.utcnow() + timedelta(days=30))
    __table_args__ = {
        'mysql_charset': 'utf8mb4',
        'mysql_collate': 'utf8mb4_unicode_ci'
    }

    @staticmethod
    def init_financial_business():
        rets = [(1, '与a公司一项支出业务', '此次支出业务花了200000元'),
                (2, '与b公司一项收入业务', '此次收入业务收了300000元')]
        for ret in rets:
            financial_business = FinancialBusiness()
            financial_business.id = ret[0]
            financial_business.name = ret[1]
            financial_business.content=ret[2]
            db.session.add(financial_business)
        db.session.commit()

    def __repr__(self):
        return f'<FinancialBusiness {self.name}>'